package com.lipaluma.field.mapper.single.impl;

import java.text.DecimalFormat;
import java.util.Locale;

import com.lipaluma.exceptions.CsvParserProcessException;
import com.lipaluma.field.mapper.mapping.FieldMappingInfo;
import com.lipaluma.field.mapper.mapping.MappingOptions;
import com.lipaluma.field.mapper.single.AbstractStandardSingleFieldMapper;
import com.lipaluma.util.ParserUtils;

/**
 * MapColumn allows primitives numerics values
 * 
 * @author Mario
 */
public abstract class AbstractNumericFieldMapper extends AbstractStandardSingleFieldMapper {

	private String pattern;
	private Locale locale;
	
	public AbstractNumericFieldMapper() {}
	/**
	 * Field Mapper that parses a numeric value
	 * @param mapping information of mapping
	 */
	public AbstractNumericFieldMapper(FieldMappingInfo mapping) {
		super(mapping);
	}
	
	/**
	 * Field Mapper that parses a numeric value
	 * @param mapping information of mapping
	 * @param pattern pattern of the numeric value
	 */
	public AbstractNumericFieldMapper(FieldMappingInfo mapping, String pattern) {
		super(mapping);
		this.pattern = pattern;
	}

	/**
	 * Field Mapper that parses a numeric value
	 * @param mapping information of mapping
	 * @param locale information of localisation to indicate how to parse the numeric value
	 * @param pattern pattern of the numeric value
	 */
	public AbstractNumericFieldMapper(FieldMappingInfo mapping, String pattern, Locale locale) {
		super(mapping);
		this.pattern = pattern;
		this.locale = locale;
	}

	@Override
	public void init(MappingOptions mappingOptions) {
		this.pattern = mappingOptions.getPattern();
		this.locale = mappingOptions.getLocale();
	}
	
	@Override
	protected Object parseExtractedValue(String value) {
		try {
			return ParserUtils.parseToType(field.getType(), value, pattern, locale);
		} catch (CsvParserProcessException e) {
			throw new CsvParserProcessException(this, "value '"+value+"' cannot be parsed to a "+field.getType().getSimpleName(), e);
		}
	}
	
	@Override
	protected Object formatValueToWriteOnRow(Object value) {
		if(pattern != null) {
			DecimalFormat format = new DecimalFormat(pattern);
			return format.format(value);
		} else 
			return value;
	}
}
